
package lohmar.ashar.android.batterySaver.helper;

import android.content.Context;
import android.content.ContextWrapper;

import lohmar.ashar.android.util.ReflectionMethodCaller;

public class NetworkHelper implements IServiceHelper {

    private ContextWrapper context;

    public NetworkHelper(ContextWrapper context) {
        this.context = context;
    }

    @Override
    public boolean isServiceEnabled() {
        try {
            return (Boolean) ReflectionMethodCaller.callGetter(getConnectivityManager(), "getMobileDataEnabled");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private Object getConnectivityManager() {
        return context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    @Override
    public boolean isServicePresent() {
        return getConnectivityManager() != null;
    }

    @Override
    public void setServiceEnabled(boolean serviceEnabled) {
        try {
            boolean currentState = isServiceEnabled();
            if (currentState != serviceEnabled) {
                ReflectionMethodCaller.callSetter(getConnectivityManager(), "setMobileDataEnabled", serviceEnabled);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getServiceName() {
        return "network";
    }

}
